# import Image
# from pillow import Image

# from pyocr import pyocr

# import pytesseract
# import torch
# import cv2

import re
import requests
import base64
from PIL import Image

import easyocr  # 导入easyocr
from paddleocr import PaddleOCR, draw_ocr
from paddleocr import PPStructure, draw_structure_result, save_structure_res
# sys.getfilesystemencoding()
import pandas as pd
import numpy as np

'''
def read_text(text_path):
    """
    传入文本(jpg、png)的绝对路径,读取文本
    :param text_path:
    :return: 文本内容
    """
    # 验证码图片转字符串
    im = Image.open(text_path)
    # 转化为8bit的黑白图片
    imgry = im.convert('L')
    # 二值化，采用阈值分割算法，threshold为分割点
    threshold = 140
    table = []
    for j in range(256):
        if j < threshold:
            table.append(0)
        else:
            table.append(1)
    out = imgry.point(table, '1')
    # 识别文本，lang参数改为chi_sim，其他代码与上面的读取验证码代码一致。
    text = pytesseract.image_to_string(out, lang="chi_sim", config='--psm 6')
    print(text)
    return text


def pyOcrDemo(fileName):
    tools = pyocr.get_available_tools()[:]
    if len(tools) == 0:
        print("No OCR tool found")
        sys.exit(1)
    print("Using '%s'" % (tools[0].get_name()))
    tools[0].image_to_string(Image.open(fileName), lang='fra',
                             builder=TextBuilder())


def GpuAvailable():
    print(torch.__version__)
    print('gpu:', torch.cuda.is_available())


def OpenCVOcr(fileName):
    gray = cv2.imread(fileName)
    gray2 = cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY)

    # 自动化阈值
    ret, gray2 = cv2.threshold(gray2, 0, 255, cv2.THRESH_OTSU)
    cv2.imwrite('hui.jpg', gray2)  # 保存灰化后的图片

    # 加了--psm 6这个参数可以识别单个数字
    text = pytesseract.image_to_string(gray2, lang='chi_sim', config='--psm 6')
    print(text)


def cnocr(fileName):

    # 第一种使用方法
    # from cnocr import CnOcr
    # ocr = CnOcr()
    # res = ocr.ocr('./mmexport1649408859072.jpg')
    # print("Predicted Chars:", res)

    # 第二种使用方法
    import mxnet as mx
    from cnocr import CnOcr
    ocr = CnOcr()
    img = mx.image.imread(fileName, 1)
    res = ocr.ocr(img)
    print("Predicted Chars:", res)
'''

def EasyOcrDemo(fileName):
    # 创建reader对象
    # reader = easyocr.Reader(['ch_sim', 'en'], gpu=False)
    reader = easyocr.Reader(['ch_sim', 'en'])
    # 读取图像
    result = reader.readtext(fileName)
    print(result)


def dataProcess(data):
    # data = {'words_result': [{'words': '16:35'}, {'words': '1令☑h'}, {'words': '结果查询'}, {'words': '●●'}, {'words': '本查询服务由上海市卫生健康委员会提供'}, {'words': '姓名'}, {'words': '赵兮扬'}, {'words': '证件类型'}, {'words': '身份证'}, {'words': '证件号码'}, {'words': '31011720160830021X'}, {'words': '样本编码'}, {'words': '93324184339'}, {
    # 'words': '采样时间'}, {'words': '2022-04-0408:15:16'}, {'words': '检测机构'}, {'words': '上海千麦博米乐医学检验所'}, {'words': '检测时间'}, {'words': '2022-04-05'}, {'words': '检测项目'}, {'words': '核酸'}, {'words': '检测结果'}, {'words': 'ORF1a/b阴性，N基因阴性'}], 'words_result_num': 23, 'log_id': 1512760388642668639}

    # print(type(data['words_result']))
    data = data['words_result']
    for i in range(len(data)):
        headData = data[i]['words']
        if "姓名" in headData:
            name = data[i + 1]['words']
            print(name, end='\t')
        elif "证件号码" in headData:
            num = data[i + 1]['words']
            print(num, end='\t')
        elif "采样时间" in headData:
            date = data[i + 1]['words']
            print(date, end='\t')
        elif "检测项目" in headData:
            project = data[i + 1]['words']
            print(project, end='\t')
        elif "检测结果" in headData:
            result = data[i + 1]['words']
            print(result)


def BaiduOcr(fileName):
    Apikey = 'gYyyTtwCOB5kr11aFYz6mdqQ'
    SecretKey = '4DiO14cpMZCQh6QkA20TCH9AsLZkeQrw'

    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?'
    host += 'grant_type=client_credentials&client_id={}&client_secret={}'.format(Apikey, SecretKey)
    response = requests.get(host)
    if response:
        access_token = response.json()['access_token']

    '''
    通用文字识别
    '''

    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    # 二进制方式打开图片文件
    f = open(fileName, 'rb')
    img = base64.b64encode(f.read())

    params = {"image": img}
    access_token = access_token
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        data = response.json()
        # print(data)
        # print(data)
        dataProcess(data)


def PaddleOCRFunc(fileName):
    # Paddleocr目前支持的多语言语种可以通过修改lang参数进行切换
    # 例如`ch`, `en`, `fr`, `german`, `korean`, `japan`
    ocr = PaddleOCR(use_angle_cls=True, lang="ch", use_gpu=True)

    result = ocr.ocr(fileName, cls=True)
    for line in result:
        print(line[1])
        # print(type(line))

    image = Image.open(fileName).convert('RGB')
    boxes = [line[0] for line in result]
    txts = [line[1][0] for line in result]
    scores = [line[1][1] for line in result]
    im_show = draw_ocr(image, boxes, txts, scores, font_path='./ppocr_img/fonts/simfang.ttf')
    im_show = Image.fromarray(im_show)
    im_show.save('result.jpg')

    # table_engine = PPStructure(show_log=True)

    # # save_folder = './output/table'
    # save_folder = "./"
    # img_path = './table/paper-image.jpg'
    # img = cv2.imread(img_path)
    # result = table_engine(img)
    # save_structure_res(result, save_folder, os.path.basename(img_path).split('.')[0])

    # for line in result:
    #     line.pop('img')
    #     print(line)

    # font_path = './fonts/simfang.ttf'  # PaddleOCR下提供字体包
    # image = Image.open(img_path).convert('RGB')
    # im_show = draw_structure_result(image, result, font_path=font_path)
    # im_show = Image.fromarray(im_show)
    # im_show.save('result.jpg')


if __name__ == "__main__":
    # GpuAvailable()
    # read_text("./mmexport1649408859072.jpg")
    # OpenCVOcr("./mmexport1649408859072.jpg")
    # cnocr('./mmexport1649408859072.jpg')
    # pyOcrDemo("./mmexport1649408859072.jpg")

    # 以下代码OK
    # PaddleOCRFunc("./y20220412223247.jpg")
    # EasyOcrDemo("./20220410082828.jpg") # CPU识别
    BaiduOcr("./y20220412223247.jpg")

    strs = '''17:28
            检测结果查询
            检测结果【阴性】
            姓名 朱卫军
            采样时间 2022-04-08 12：28
            试剂编码 48
            检测项目 新冠抗原
            '''

    # name = re.findall('(?<=姓名 ).*', strs)
    # time = re.findall('(?<=采样时间 ).*', strs)
    # result = re.findall('(?<=【).*(?=】)', strs)
    # print(name)
    # print(time)
    # print(result)

    # info1 = name + time + result
    # info1 = np.array(info1).reshape(1, 3)

    # df = pd.DataFrame(info1, columns=['姓名', '时间', '检测结果'])
    # df.to_excel('核酸结果.xlsx', index=False)
